{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "google",
   "metadata": {},
   "source": [
    "##### Copyright 2025 Google LLC."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "apache",
   "metadata": {},
   "source": [
    "Licensed under the Apache License, Version 2.0 (the \"License\");\n",
    "you may not use this file except in compliance with the License.\n",
    "You may obtain a copy of the License at\n",
    "\n",
    "    http://www.apache.org/licenses/LICENSE-2.0\n",
    "\n",
    "Unless required by applicable law or agreed to in writing, software\n",
    "distributed under the License is distributed on an \"AS IS\" BASIS,\n",
    "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
    "See the License for the specific language governing permissions and\n",
    "limitations under the License.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "basename",
   "metadata": {},
   "source": [
    "# balance_group_sat"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "link",
   "metadata": {},
   "source": [
    "<table align=\"left\">\n",
    "<td>\n",
    "<a href=\"https://colab.research.google.com/github/google/or-tools/blob/main/examples/notebook/examples/balance_group_sat.ipynb\"><img src=\"https://raw.githubusercontent.com/google/or-tools/main/tools/colab_32px.png\"/>Run in Google Colab</a>\n",
    "</td>\n",
    "<td>\n",
    "<a href=\"https://github.com/google/or-tools/blob/main/examples/python/balance_group_sat.py\"><img src=\"https://raw.githubusercontent.com/google/or-tools/main/tools/github_32px.png\"/>View source on GitHub</a>\n",
    "</td>\n",
    "</table>"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "doc",
   "metadata": {},
   "source": [
    "First, you must install [ortools](https://pypi.org/project/ortools/) package in this colab."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "install",
   "metadata": {},
   "outputs": [],
   "source": [
    "%pip install ortools"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "description",
   "metadata": {},
   "source": [
    "\n",
    "We are trying to group items in equal sized groups.\n",
    "\n",
    "Each item has a color and a value. We want the sum of values of each group to\n",
    "be as close to the average as possible.\n",
    "Furthermore, if one color is an a group, at least k items with this color must\n",
    "be in that group.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "code",
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import Dict, Sequence\n",
    "\n",
    "from ortools.sat.python import cp_model\n",
    "\n",
    "\n",
    "# Create a solution printer.\n",
    "class SolutionPrinter(cp_model.CpSolverSolutionCallback):\n",
    "    \"\"\"Print intermediate solutions.\"\"\"\n",
    "\n",
    "    def __init__(self, values, colors, all_groups, all_items, item_in_group):\n",
    "        cp_model.CpSolverSolutionCallback.__init__(self)\n",
    "        self.__solution_count = 0\n",
    "        self.__values = values\n",
    "        self.__colors = colors\n",
    "        self.__all_groups = all_groups\n",
    "        self.__all_items = all_items\n",
    "        self.__item_in_group = item_in_group\n",
    "\n",
    "    def on_solution_callback(self):\n",
    "        print(f\"Solution {self.__solution_count}\")\n",
    "        self.__solution_count += 1\n",
    "\n",
    "        print(f\"  objective value = {self.objective_value}\")\n",
    "        groups = {}\n",
    "        sums = {}\n",
    "        for g in self.__all_groups:\n",
    "            groups[g] = []\n",
    "            sums[g] = 0\n",
    "            for item in self.__all_items:\n",
    "                if self.boolean_value(self.__item_in_group[(item, g)]):\n",
    "                    groups[g].append(item)\n",
    "                    sums[g] += self.__values[item]\n",
    "\n",
    "        for g in self.__all_groups:\n",
    "            group = groups[g]\n",
    "            print(f\"group {g}: sum = {sums[g]:0.2f} [\", end=\"\")\n",
    "            for item in group:\n",
    "                value = self.__values[item]\n",
    "                color = self.__colors[item]\n",
    "                print(f\" ({item}, {value}, {color})\", end=\"\")\n",
    "            print(\"]\")\n",
    "\n",
    "\n",
    "def main(argv: Sequence[str]) -> None:\n",
    "    \"\"\"Solves a group balancing problem.\"\"\"\n",
    "\n",
    "    if len(argv) > 1:\n",
    "        raise app.UsageError(\"Too many command-line arguments.\")\n",
    "    # Data.\n",
    "    num_groups = 10\n",
    "    num_items = 100\n",
    "    num_colors = 3\n",
    "    min_items_of_same_color_per_group = 4\n",
    "\n",
    "    all_groups = range(num_groups)\n",
    "    all_items = range(num_items)\n",
    "    all_colors = range(num_colors)\n",
    "\n",
    "    # values for each items.\n",
    "    values = [1 + i + (i * i // 200) for i in all_items]\n",
    "    # Color for each item (simple modulo).\n",
    "    colors = [i % num_colors for i in all_items]\n",
    "\n",
    "    sum_of_values = sum(values)\n",
    "    average_sum_per_group = sum_of_values // num_groups\n",
    "\n",
    "    num_items_per_group = num_items // num_groups\n",
    "\n",
    "    # Collect all items in a given color.\n",
    "    items_per_color: Dict[int, list[int]] = {}\n",
    "    for color in all_colors:\n",
    "        items_per_color[color] = []\n",
    "        for i in all_items:\n",
    "            if colors[i] == color:\n",
    "                items_per_color[color].append(i)\n",
    "\n",
    "    print(\n",
    "        f\"Model has {num_items} items, {num_groups} groups, and\" f\" {num_colors} colors\"\n",
    "    )\n",
    "    print(f\"  average sum per group = {average_sum_per_group}\")\n",
    "\n",
    "    # Model.\n",
    "\n",
    "    model = cp_model.CpModel()\n",
    "\n",
    "    item_in_group = {}\n",
    "    for i in all_items:\n",
    "        for g in all_groups:\n",
    "            item_in_group[(i, g)] = model.new_bool_var(f\"item {i} in group {g}\")\n",
    "\n",
    "    # Each group must have the same size.\n",
    "    for g in all_groups:\n",
    "        model.add(sum(item_in_group[(i, g)] for i in all_items) == num_items_per_group)\n",
    "\n",
    "    # One item must belong to exactly one group.\n",
    "    for i in all_items:\n",
    "        model.add(sum(item_in_group[(i, g)] for g in all_groups) == 1)\n",
    "\n",
    "    # The deviation of the sum of each items in a group against the average.\n",
    "    e = model.new_int_var(0, 550, \"epsilon\")\n",
    "\n",
    "    # Constrain the sum of values in one group around the average sum per group.\n",
    "    for g in all_groups:\n",
    "        model.add(\n",
    "            sum(item_in_group[(i, g)] * values[i] for i in all_items)\n",
    "            <= average_sum_per_group + e\n",
    "        )\n",
    "        model.add(\n",
    "            sum(item_in_group[(i, g)] * values[i] for i in all_items)\n",
    "            >= average_sum_per_group - e\n",
    "        )\n",
    "\n",
    "    # color_in_group variables.\n",
    "    color_in_group = {}\n",
    "    for g in all_groups:\n",
    "        for c in all_colors:\n",
    "            color_in_group[(c, g)] = model.new_bool_var(f\"color {c} is in group {g}\")\n",
    "\n",
    "    # Item is in a group implies its color is in that group.\n",
    "    for i in all_items:\n",
    "        for g in all_groups:\n",
    "            model.add_implication(item_in_group[(i, g)], color_in_group[(colors[i], g)])\n",
    "\n",
    "    # If a color is in a group, it must contains at least\n",
    "    # min_items_of_same_color_per_group items from that color.\n",
    "    for c in all_colors:\n",
    "        for g in all_groups:\n",
    "            literal = color_in_group[(c, g)]\n",
    "            model.add(\n",
    "                sum(item_in_group[(i, g)] for i in items_per_color[c])\n",
    "                >= min_items_of_same_color_per_group\n",
    "            ).only_enforce_if(literal)\n",
    "\n",
    "    # Compute the maximum number of colors in a group.\n",
    "    max_color = num_items_per_group // min_items_of_same_color_per_group\n",
    "\n",
    "    # Redundant constraint, it helps with solving time.\n",
    "    if max_color < num_colors:\n",
    "        for g in all_groups:\n",
    "            model.add(sum(color_in_group[(c, g)] for c in all_colors) <= max_color)\n",
    "\n",
    "    # minimize epsilon\n",
    "    model.minimize(e)\n",
    "\n",
    "    solver = cp_model.CpSolver()\n",
    "    # solver.parameters.log_search_progress = True\n",
    "    solver.parameters.num_workers = 16\n",
    "    solution_printer = SolutionPrinter(\n",
    "        values, colors, all_groups, all_items, item_in_group\n",
    "    )\n",
    "    status = solver.solve(model, solution_printer)\n",
    "\n",
    "    if status == cp_model.OPTIMAL:\n",
    "        print(f\"Optimal epsilon: {solver.objective_value}\")\n",
    "        print(solver.response_stats())\n",
    "    else:\n",
    "        print(\"No solution found\")\n",
    "\n",
    "\n",
    "main()\n",
    "\n"
   ]
  }
 ],
 "metadata": {
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
